﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;
using Twi.DataAccess.DBUtility;
using System.Configuration;

namespace Twi.COMMON.WCF
{
    public class FileManagement
    {


        //文件根路径
        public static string FileRootPath = ConfigurationManager.AppSettings["FileRootPath"];

        /// <summary>
        /// 文件存储类型
        /// </summary>
        public static int FileStore
        {
            get
            {
                if (ConfigurationManager.AppSettings["FileStore"] == null)
                {
                    return 1;
                }
                else
                {
                    return int.Parse(ConfigurationManager.AppSettings["FileStore"]);
                }
            }
        }


        #region 保存文件
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="fileID"></param>
        /// <param name="fileName"></param>
        /// <param name="fileCategory"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public static XElement Create(Stream fileData, Guid fileID, string fileName, string fileCategory, int uid, Guid fileGroupID = new Guid())
        {
            long fileSize = 0;
            if (FileStore == 2)
            {
                #region 文件保存在数据库
                byte[] data;
                byte[] buffer = new byte[4096];
                using (fileData)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        int read;
                        while ((read = fileData.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                        data = ms.ToArray();
                    }
                }

                Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                {
                    cmd.SetParameter("FileID", fileID);
                    cmd.SetParameter("FileCategory", fileCategory);
                    cmd.SetParameter("FileName", Path.GetFileNameWithoutExtension(fileName));
                    cmd.SetParameter("Extension", Path.GetExtension(fileName));
                    cmd.SetParameter("FileSize", fileSize);
                    cmd.SetParameter("UploadDate", DateTime.Now);
                    cmd.SetParameter("DownloadCount", 0);
                    cmd.SetParameter("UploadUserID", uid);
                    cmd.SetParameter("RelativePath", "");
                    cmd.SetParameter("LocalPath", "");
                    cmd.SetParameter("MachineName", Environment.MachineName);
                    cmd.SetParameter("STOREFLAG", 2);
                    cmd.SetParameter("FILEDATA", data);

                    cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName,STOREFLAG,FILEDATA) 
VALUES( {0}FileID,{0}FileName,{0}Extension,{0}FileSize
,{0}FileCategory,{0}UploadDate,{0}DownloadCount,{0}UploadUserID,{0}RelativePath,{0}LocalPath,{0}MachineName,{0}STOREFLAG,{0}FILEDATA)", DBHelper.ParamePrx);

                    cmd.ExecuteNonQuery();
                };
                return ProcessRequestComm.Process(processDelegate);
                #endregion
            }
            else
            {
                #region 文件保存在硬盘上
                string[] savePaths = GetNewFilePath(fileID, fileCategory);  //保存目录 0 为相对路径  1为绝对路径
                //新增文件
                byte[] buffer = new byte[4096];
                using (fileData)
                {
                    using (FileStream fs = new FileStream(savePaths[1], FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                    {
                        int read;
                        while ((read = fileData.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            fs.Write(buffer, 0, read);
                        }
                    }
                }

                Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                {
                    cmd.SetParameter("FileID", fileID);
                    cmd.SetParameter("FileCategory", fileCategory);
                    cmd.SetParameter("FileName", Path.GetFileNameWithoutExtension(fileName));
                    cmd.SetParameter("Extension", Path.GetExtension(fileName));
                    cmd.SetParameter("FileSize", fileSize);
                    cmd.SetParameter("UploadDate", DateTime.Now);
                    cmd.SetParameter("DownloadCount", 0);
                    cmd.SetParameter("UploadUserID", uid);
                    cmd.SetParameter("RelativePath", savePaths[0]);
                    cmd.SetParameter("LocalPath", savePaths[1]);
                    cmd.SetParameter("MachineName", Environment.MachineName);
                    cmd.SetParameter("STOREFLAG", 1);
                    cmd.SetParameter("FileGroupID", fileGroupID);
                    cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName, STOREFLAG,FileGroupID) 
VALUES( {0}FileID,{0}FileName,{0}Extension,{0}FileSize
,{0}FileCategory,{0}UploadDate,{0}DownloadCount,{0}UploadUserID,{0}RelativePath,{0}LocalPath,{0}MachineName, {0}STOREFLAG,{0}FileGroupID)", DBHelper.ParamePrx);

                    cmd.ExecuteNonQuery();
                };
                return ProcessRequestComm.Process(processDelegate);
                #endregion
            }
        }
        #endregion
        #region 保存并加密文件
        public static XElement Create(Stream fileData, Guid fileID, string fileName, string fileCategory, int uid, Guid encryptFileID, string encryptFileCategory)
        {
            long fileSize = 0;
            if (FileStore == 2)
            {
                #region 数据库中存储文件

                byte[] data;
                byte[] buffer = new byte[4096];
                using (fileData)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        int read;
                        while ((read = fileData.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                        data = ms.ToArray();
                    }
                }

                byte[] encryptBuffer = FileProtector.EncryptFile(data);

                Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                {
                    cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName,STOREFLAG,FILEDATA) 
VALUES( {0}FileID,{0}FileName,{0}Extension,{0}FileSize
,{0}FileCategory,{0}UploadDate,{0}DownloadCount,{0}UploadUserID,{0}RelativePath,{0}LocalPath,{0}MachineName,{0}STOREFLAG,{0}FILEDATA)", DBHelper.ParamePrx);


                    cmd.SetParameter("FileName", Path.GetFileNameWithoutExtension(fileName));
                    cmd.SetParameter("FileSize", fileSize);
                    cmd.SetParameter("UploadDate", DateTime.Now);
                    cmd.SetParameter("DownloadCount", 0);
                    cmd.SetParameter("UploadUserID", uid);
                    cmd.SetParameter("MachineName", Environment.MachineName);
                    cmd.SetParameter("RelativePath", "");
                    cmd.SetParameter("LocalPath", "");
                    cmd.SetParameter("STOREFLAG", 2);

                    #region 保存常规文件
                    cmd.SetParameter("FileID", fileID);
                    cmd.SetParameter("FileCategory", fileCategory);
                    cmd.SetParameter("Extension", Path.GetExtension(fileName));
                    cmd.SetParameter("FILEDATA", data);

                    cmd.ExecuteNonQuery();
                    #endregion

                    #region 保存加密文件
                    cmd.SetParameter("FileID", encryptFileID);
                    cmd.SetParameter("FileCategory", encryptFileCategory);
                    cmd.SetParameter("Extension", ".gsf");
                    cmd.SetParameter("FILEDATA", encryptBuffer);

                    cmd.ExecuteNonQuery();
                    #endregion
                };
                return ProcessRequestComm.Process(processDelegate);
                #endregion
            }
            else
            {
                #region 硬盘上存储文件
                string[] savePaths = GetNewFilePath(fileID, fileCategory);  //保存目录 0 为相对路径  1为绝对路径
                //新增文件
                FileStream saveStream;
                using (saveStream = new FileStream(savePaths[1], FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                {
                    byte[] buffer = new byte[4096];
                    int count = 0;
                    while ((count = fileData.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        saveStream.Write(buffer, 0, count);
                    }
                    fileSize = saveStream.Length;
                    fileData.Close();
                }

                string[] encryptSavePaths = GetNewFilePath(encryptFileID, encryptFileCategory);  //保存目录 0 为相对路径  1为绝对路径
                FileProtector.EncryptFile(savePaths[1], encryptSavePaths[1], "");

                Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                {
                    cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName,STOREFLAG) 
VALUES( {0}FileID,{0}FileName,{0}Extension,{0}FileSize
,{0}FileCategory,{0}UploadDate,{0}DownloadCount,{0}UploadUserID,{0}RelativePath,{0}LocalPath,{0}MachineName,{0}STOREFLAG)", DBHelper.ParamePrx);

                    cmd.SetParameter("FileName", Path.GetFileNameWithoutExtension(fileName));
                    cmd.SetParameter("FileSize", fileSize);
                    cmd.SetParameter("UploadDate", DateTime.Now);
                    cmd.SetParameter("DownloadCount", 0);
                    cmd.SetParameter("UploadUserID", uid);
                    cmd.SetParameter("MachineName", Environment.MachineName);
                    cmd.SetParameter("STOREFLAG", 1);

                    #region 保存常规文件
                    cmd.SetParameter("FileID", fileID);
                    cmd.SetParameter("FileCategory", fileCategory);
                    cmd.SetParameter("Extension", Path.GetExtension(fileName));
                    cmd.SetParameter("RelativePath", savePaths[0]);
                    cmd.SetParameter("LocalPath", savePaths[1]);

                    cmd.ExecuteNonQuery();
                    #endregion

                    #region 保存加密文件
                    cmd.SetParameter("FileID", encryptFileID);
                    cmd.SetParameter("FileCategory", encryptFileCategory);
                    cmd.SetParameter("Extension", ".gsf");
                    cmd.SetParameter("RelativePath", encryptSavePaths[0]);
                    cmd.SetParameter("LocalPath", encryptSavePaths[1]);

                    cmd.ExecuteNonQuery();
                    #endregion

                };
                return ProcessRequestComm.Process(processDelegate);
                #endregion
            }
        }
        #endregion

        #region 保存到指定服务器
        public static XElement CreateByUrl(Stream fileData, Guid fileID, string fileName, string fileCategory, int uid, string URL, Guid fileGroupID = new Guid())
        {
            string fname = fileName.Substring(0, fileName.LastIndexOf('.'));
            string fExpandName = fileName.Substring(fileName.LastIndexOf('.'));
            string filename = String.Format("{0}_{1}{2}", fname, DateTime.Now.ToString("yyyyMMddHHmmss"), fExpandName);
            long fileSize = 0;
            if (FileStore == 2)
            {
                #region 文件保存在数据库
                byte[] data;
                byte[] buffer = new byte[4096];
                using (fileData)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        int read;
                        while ((read = fileData.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                        data = ms.ToArray();
                    }
                }

                Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                {
                    cmd.SetParameter("FileID", fileID);
                    cmd.SetParameter("FileCategory", fileCategory);
                    cmd.SetParameter("FileName", Path.GetFileNameWithoutExtension(fileName));
                    cmd.SetParameter("Extension", Path.GetExtension(fileName));
                    cmd.SetParameter("FileSize", fileSize);
                    cmd.SetParameter("UploadDate", DateTime.Now);
                    cmd.SetParameter("DownloadCount", 0);
                    cmd.SetParameter("UploadUserID", uid);
                    cmd.SetParameter("RelativePath", "");
                    cmd.SetParameter("LocalPath", "");
                    cmd.SetParameter("MachineName", Environment.MachineName);
                    cmd.SetParameter("STOREFLAG", 2);
                    cmd.SetParameter("FILEDATA", data);
                    cmd.SetParameter("URL", URL);

                    cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName,STOREFLAG,FILEDATA,URL) 
VALUES( {0}FileID,{0}FileName,{0}Extension,{0}FileSize
,{0}FileCategory,{0}UploadDate,{0}DownloadCount,{0}UploadUserID,{0}RelativePath,{0}LocalPath,{0}MachineName,{0}STOREFLAG,{0}FILEDATA,{0}URL)", DBHelper.ParamePrx);

                    cmd.ExecuteNonQuery();
                };
                return ProcessRequestComm.Process(processDelegate);
                #endregion
            }
            else
            {
                #region 文件保存在硬盘上
                string[] savePaths = GetNewFilePath(fileID, fileCategory, filename, false);  //保存目录 0 为相对路径  1为绝对路径
                //新增文件
                byte[] buffer = new byte[4096];
                using (fileData)
                {
                    using (FileStream fs = new FileStream(savePaths[1], FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                    {
                        int read;
                        while ((read = fileData.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            fs.Write(buffer, 0, read);
                        }
                    }
                }

                Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                {
                    cmd.SetParameter("FileID", fileID);
                    cmd.SetParameter("FileCategory", fileCategory);
                    cmd.SetParameter("FileName", Path.GetFileNameWithoutExtension(fileName));
                    cmd.SetParameter("Extension", Path.GetExtension(fileName));
                    cmd.SetParameter("FileSize", fileSize);
                    cmd.SetParameter("UploadDate", DateTime.Now);
                    cmd.SetParameter("DownloadCount", 0);
                    cmd.SetParameter("UploadUserID", uid);
                    cmd.SetParameter("RelativePath", savePaths[0]);
                    cmd.SetParameter("LocalPath", savePaths[1]);
                    cmd.SetParameter("MachineName", Environment.MachineName);
                    cmd.SetParameter("STOREFLAG", 1);
                    cmd.SetParameter("FileGroupID", fileGroupID);
                    cmd.SetParameter("URL", URL);
                    cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName, STOREFLAG,FileGroupID,URL) 
VALUES( {0}FileID,{0}FileName,{0}Extension,{0}FileSize
,{0}FileCategory,{0}UploadDate,{0}DownloadCount,{0}UploadUserID,{0}RelativePath,{0}LocalPath,{0}MachineName, {0}STOREFLAG,{0}FileGroupID,{0}URL)", DBHelper.ParamePrx);

                    cmd.ExecuteNonQuery();
                };
                return ProcessRequestComm.Process(processDelegate);
                #endregion
            }
        }
        #endregion

        #region 修改文件，更新
        /// <summary>
        /// 修改文件，更新
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="fileID"></param>
        /// <param name="fileName"></param>
        /// <param name="fileCategory"></param>
        /// <returns></returns>
        public static XElement Update(Stream fileData, string fileName, XElement xeFile, int uid)
        {
            long fileSize = 0;

            if (FileStore == 2)
            {
                #region 修改存储在数据库中的文件
                //由于这里的Stream.Length不能使用，只能用如下方式
                byte[] data;
                byte[] buffer = new byte[4096];
                using (fileData)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        int read;
                        while ((read = fileData.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                        data = ms.ToArray();
                    }
                }
                Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                {
                    cmd.SetParameter("FILEDATA", data);
                    cmd.SetParameter("FileName", Path.GetFileNameWithoutExtension(fileName));
                    cmd.SetParameter("Extension", Path.GetExtension(fileName));
                    cmd.SetParameter("FileSize", fileSize);
                    cmd.SetParameter("LastUpdateUserID", uid);
                    cmd.SetParameter("LastUpdateDate", DateTime.Now);
                    cmd.SetParameter("FileID", new Guid(xeFile.Element("FileID").Value));

                    cmd.CommandText = string.Format(@"UPDATE gnl_File SET FILEDATA={0}FILEDATA, FileName={0}FileName, Extension={0}Extension, FileSize={0}FileSize
                , LastUpdateUserID={0}LastUpdateUserID, LastUpdateDate={0}LastUpdateDate WHERE FileID = {0}FileID", DBHelper.ParamePrx);
                    cmd.ExecuteNonQuery();
                };
                return ProcessRequestComm.Process(processDelegate);
                #endregion
            }
            else
            {
                #region 修改存储在硬盘上的文件
                //保存文件
                //FileStream saveStream;
                //using (saveStream = new FileStream(GetFilePath(xeFile), FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                //{
                //    byte[] buffer = new byte[4096];
                //    int count = 0;
                //    while ((count = fileData.Read(buffer, 0, buffer.Length)) > 0)
                //    {
                //        saveStream.Write(buffer, 0, count);
                //    }
                //    fileSize = saveStream.Length;
                //    fileData.Close();
                //}

                string filePath = GetFilePath(xeFile);
                File.Delete(filePath);

                byte[] buffer = new byte[4096];
                using (fileData)
                {
                    using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        int read;
                        while ((read = fileData.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            fs.Write(buffer, 0, read);
                        }
                    }
                }

                Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                {
                    cmd.SetParameter("FileName", Path.GetFileNameWithoutExtension(fileName));
                    cmd.SetParameter("Extension", Path.GetExtension(fileName));
                    cmd.SetParameter("FileSize", fileSize);
                    cmd.SetParameter("LastUpdateUserID", uid);
                    cmd.SetParameter("LastUpdateDate", DateTime.Now);
                    cmd.SetParameter("FileID", new Guid(xeFile.Element("FileID").Value));

                    cmd.CommandText = string.Format(@"UPDATE gnl_File SET FileName={0}FileName, Extension={0}Extension, FileSize={0}FileSize
                , LastUpdateUserID={0}LastUpdateUserID, LastUpdateDate={0}LastUpdateDate WHERE FileID = {0}FileID", DBHelper.ParamePrx);
                    cmd.ExecuteNonQuery();
                };
                return ProcessRequestComm.Process(processDelegate);
                #endregion
            }
        }
        #endregion

        #region 拷贝原文件
        /// <summary>
        /// 拷贝原文件
        /// </summary>
        /// <param name="fileLocalPath">拷贝文件路径</param>
        /// <param name="newFileID">新文件ID</param>
        /// <param name="fileName"></param>
        /// <param name="fileCategory"></param>
        /// <param name="uid"></param>
        public static void Copy(string fileLocalPath, Guid newFileID, string fileName, string fileCategory, int uid, string extension = "")
        {
            if (FileStore == 2)
            {
                #region 拷贝存储到数据库
                FileStream fileData = File.OpenRead(fileLocalPath);
                byte[] data;
                byte[] buffer = new byte[4096];
                using (fileData)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        int read;
                        while ((read = fileData.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                        data = ms.ToArray();
                    }
                }

                using (TwiCommand cmd = DBHelper.CreateCommand())
                {
                    cmd.SetParameter("FileID", newFileID);
                    cmd.SetParameter("FileCategory", fileCategory);
                    cmd.SetParameter("FileName", Path.GetFileNameWithoutExtension(fileName));
                    cmd.SetParameter("Extension", extension == "" ? Path.GetExtension(fileName) : extension);
                    cmd.SetParameter("FileSize", fileData.Length);
                    cmd.SetParameter("UploadDate", DateTime.Now);
                    cmd.SetParameter("DownloadCount", 0);
                    cmd.SetParameter("UploadUserID", uid);
                    cmd.SetParameter("RelativePath", "");
                    cmd.SetParameter("LocalPath", "");
                    cmd.SetParameter("MachineName", Environment.MachineName);
                    cmd.SetParameter("STOREFLAG", 2);
                    cmd.SetParameter("FILEDATA", data);

                    cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName, STOREFLAG, FILEDATA) 
VALUES( {0}FileID,{0}FileName,{0}Extension,{0}FileSize,{0}FileCategory,{0}UploadDate,{0}DownloadCount
,{0}UploadUserID,{0}RelativePath,{0}LocalPath,{0}MachineName,{0}STOREFLAG,{0}FILEDATA)", DBHelper.ParamePrx);

                    cmd.ExecuteNonQuery();
                }
                #endregion
            }
            else
            {
                #region 拷贝存储到硬盘上
                string[] savePaths = GetNewFilePath(newFileID, fileCategory);  //保存目录 0 为相对路径  1为绝对路径

                FileInfo finfo = new FileInfo(fileLocalPath);
                finfo.CopyTo(savePaths[1], true);

                using (TwiCommand cmd = DBHelper.CreateCommand())
                {
                    cmd.SetParameter("FileID", newFileID);
                    cmd.SetParameter("FileCategory", fileCategory);
                    cmd.SetParameter("FileName", Path.GetFileNameWithoutExtension(fileName));
                    cmd.SetParameter("Extension", extension == "" ? Path.GetExtension(fileName) : extension);
                    cmd.SetParameter("FileSize", finfo.Length);
                    cmd.SetParameter("UploadDate", DateTime.Now);
                    cmd.SetParameter("DownloadCount", 0);
                    cmd.SetParameter("UploadUserID", uid);
                    cmd.SetParameter("RelativePath", savePaths[0]);
                    cmd.SetParameter("LocalPath", savePaths[1]);
                    cmd.SetParameter("MachineName", Environment.MachineName);
                    cmd.SetParameter("STOREFLAG", 1);

                    cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName, STOREFLAG) 
VALUES( {0}FileID,{0}FileName,{0}Extension,{0}FileSize
,{0}FileCategory,{0}UploadDate,{0}DownloadCount,{0}UploadUserID,{0}RelativePath,{0}LocalPath,{0}MachineName,{0}STOREFLAG)", DBHelper.ParamePrx);

                    cmd.ExecuteNonQuery();
                }
                #endregion
            }
        }
        #endregion

        #region 拷贝文件（通过文件ID）
        /// <summary>
        /// 拷贝文件（通过文件ID）
        /// </summary>
        /// <param name="newFileID"></param>
        /// <param name="newFileCategory"></param>
        /// <param name="copyFileID"></param>
        /// <param name="uid"></param>
        public static XElement CopyByFileID(Guid newFileID, string newFileCategory, Guid copyFileID, int uid, string url = "")
        {
            int executeNonQuery = 0;
            if (url == "")
            {
                if (FileStore == 2)
                {
                    #region 数据库存储模式拷贝
                    Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                    {
                        cmd.SetParameter("NewFileID", newFileID);
                        cmd.SetParameter("NewFileCategory", newFileCategory);
                        cmd.SetParameter("STOREFLAG", 2);
                        cmd.SetParameter("CopyFileID", copyFileID);

                        cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FILECATEGORY ,UPLOADDATE,DOWNLOADCOUNT,UPLOADUSERID,RELATIVEPATH,LOCALPATH,MACHINENAME, STOREFLAG, FILEDATA) 
SELECT {0}NewFileID,FileName,Extension,FileSize
,{0}NewFileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName, {0}STOREFLAG, FILEDATA FROM gnl_File
WHERE FileID={0}CopyFileID", DBHelper.ParamePrx);

                        executeNonQuery = cmd.ExecuteNonQuery();
                    };
                    return ProcessRequestComm.Process(processDelegate);
                    #endregion
                }
                else
                {
                    XElement xeCopyFileInfo = GetFile(copyFileID);
                    #region 硬盘存储模式拷贝
                    string[] savePaths = GetNewFilePath(newFileID, newFileCategory);  //保存目录 0 为相对路径  1为绝对路径

                    FileInfo finfo = new FileInfo(xeCopyFileInfo.Element("LocalPath").Value);
                    finfo.CopyTo(savePaths[1], true);

                    Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                    {
                        cmd.SetParameter("FileID", newFileID);
                        cmd.SetParameter("FileCategory", newFileCategory);
                        cmd.SetParameter("FileName", xeCopyFileInfo.Element("FileName").Value);
                        cmd.SetParameter("Extension", xeCopyFileInfo.Element("Extension").Value);
                        cmd.SetParameter("FileSize", xeCopyFileInfo.Element("FileSize").Value);
                        cmd.SetParameter("UploadDate", DateTime.Now);
                        cmd.SetParameter("DownloadCount", 0);
                        cmd.SetParameter("UploadUserID", uid);
                        cmd.SetParameter("RelativePath", savePaths[0]);
                        cmd.SetParameter("LocalPath", savePaths[1]);
                        cmd.SetParameter("MachineName", Environment.MachineName);
                        cmd.SetParameter("STOREFLAG", 1);

                        cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName, STOREFLAG) 
VALUES( {0}FileID,{0}FileName,{0}Extension,{0}FileSize
,{0}FileCategory,{0}UploadDate,{0}DownloadCount,{0}UploadUserID,{0}RelativePath,{0}LocalPath,{0}MachineName,{0}STOREFLAG)", DBHelper.ParamePrx);

                        executeNonQuery = cmd.ExecuteNonQuery();
                    };
                    return ProcessRequestComm.Process(processDelegate);
                    #endregion
                }
            }
            else {
                if (FileStore == 2)
                {
                    #region 数据库存储模式拷贝
                    Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                    {
                        cmd.SetParameter("NewFileID", newFileID);
                        cmd.SetParameter("NewFileCategory", newFileCategory);
                        cmd.SetParameter("STOREFLAG", 2);
                        cmd.SetParameter("CopyFileID", copyFileID);
                        cmd.SetParameter("URL", url);

                        cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FILECATEGORY ,UPLOADDATE,DOWNLOADCOUNT,UPLOADUSERID,RELATIVEPATH,LOCALPATH,MACHINENAME, STOREFLAG, FILEDATA,URL) 
SELECT {0}NewFileID,FileName,Extension,FileSize
,{0}NewFileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName, {0}STOREFLAG, FILEDATA ,{0}URL FROM gnl_File
WHERE FileID={0}CopyFileID", DBHelper.ParamePrx);

                        executeNonQuery = cmd.ExecuteNonQuery();
                    };
                    return ProcessRequestComm.Process(processDelegate);
                    #endregion
                }
                else
                {
                    XElement xeCopyFileInfo = GetFile(copyFileID);
                    #region 硬盘存储模式拷贝
                    string filename = String.Format("{0}_{1}{2}", xeCopyFileInfo.Element("FileName").Value, DateTime.Now.ToString("yyyyMMddHHmmss"), xeCopyFileInfo.Element("Extension").Value);
                    string[] savePaths = GetNewFilePath(newFileID, newFileCategory,filename,false);  //保存目录 0 为相对路径  1为绝对路径

                    FileInfo finfo = new FileInfo(xeCopyFileInfo.Element("LocalPath").Value);
                    finfo.CopyTo(savePaths[1], true);

                    Action<ResponseMessageInfo, TwiCommand> processDelegate = (ResponseMessageInfo resInfo, TwiCommand cmd) =>
                    {
                        cmd.SetParameter("FileID", newFileID);
                        cmd.SetParameter("FileCategory", newFileCategory);
                        cmd.SetParameter("FileName", xeCopyFileInfo.Element("FileName").Value);
                        cmd.SetParameter("Extension", xeCopyFileInfo.Element("Extension").Value);
                        cmd.SetParameter("FileSize", xeCopyFileInfo.Element("FileSize").Value);
                        cmd.SetParameter("UploadDate", DateTime.Now);
                        cmd.SetParameter("DownloadCount", 0);
                        cmd.SetParameter("UploadUserID", uid);
                        cmd.SetParameter("RelativePath", savePaths[0]);
                        cmd.SetParameter("LocalPath", savePaths[1]);
                        cmd.SetParameter("MachineName", Environment.MachineName);
                        cmd.SetParameter("STOREFLAG", 1);
                        cmd.SetParameter("URL",url);


                        cmd.CommandText = string.Format(@"INSERT INTO gnl_File (FileID,FileName,Extension,FileSize
,FileCategory ,UploadDate,DownloadCount,UploadUserID,RelativePath,LocalPath,MachineName, STOREFLAG,URL) 
VALUES( {0}FileID,{0}FileName,{0}Extension,{0}FileSize
,{0}FileCategory,{0}UploadDate,{0}DownloadCount,{0}UploadUserID,{0}RelativePath,{0}LocalPath,{0}MachineName,{0}STOREFLAG,{0}URL)", DBHelper.ParamePrx);

                        executeNonQuery = cmd.ExecuteNonQuery();
                    };
                    return ProcessRequestComm.Process(processDelegate);
                    #endregion
                }
            }
        }
        #endregion

        #region 获取新的保存目录 0 为相对路径  1为绝对路径
        //获取新的保存目录 0 为相对路径  1为绝对路径
        public static string[] GetNewFilePath(Guid fileid, string category, string fileName = "", bool isCreateByDate = true)
        {
            string saveDir = "";
            if (isCreateByDate)
            {
                saveDir = string.Format(@"\{0}\{1}", category, DateTime.Now.ToString("yyyyMM"));
            }
            else
            {
                saveDir = string.Format(@"\{0}", category);//用于把整个路径传过来(文件夹/报验日期/机构业务编号)
            }
            if (Directory.Exists(FileRootPath + saveDir))
            {

            }
            else
            {
                Directory.CreateDirectory(FileRootPath + saveDir);
            }
            if (fileName == "")
            {
                return new string[] { saveDir + @"\" + fileid.ToString().ToLower(),
                FileRootPath + saveDir + @"\" + fileid.ToString().ToLower() };
            }
            else
            {
                return new string[] { saveDir + @"\" + fileName.ToLower(),
                FileRootPath + saveDir + @"\" +fileName.ToLower() };
            }
        }
        #endregion
        #region 获取文件的保存路径(全路径)
        /// <summary>
        /// 获取文件的保存路径(全路径)
        /// </summary>
        /// <param name="xeFile"></param>
        /// <returns></returns>
        public static string GetFilePath(XElement xeFile)
        {
            string serverPath = "";
            if (xeFile.Element("RelativePath").Value == "") //用原方式获取路径
            {
                serverPath = string.Format(@"{0}\{1}\{2}",
                     FileManagement.FileRootPath,
                     xeFile.Element("FileType").Value,
                     xeFile.Element("FileID").Value);
            }
            else
            {
                serverPath = FileManagement.FileRootPath + xeFile.Element("RelativePath").Value;
            }
            return serverPath;
        }
        #endregion

        public static Stream GetFileContent(Guid fileID)
        {
            Stream filestream = null;
            XElement xeFile = GetFile(fileID);
            if (xeFile != null)
            {
                bool isDownload = false;
                if (xeFile.Element("STOREFLAG").GetValue<int>(0) == 2)
                {
                    #region 数据库中获得下载文件

                    using (TwiCommand cmd = DBHelper.CreateCommand())
                    {
                        cmd.SetParameter("FileID", fileID);
                        cmd.CommandText = string.Format("SELECT FileData FROM gnl_File WHERE FileID ={0}FileID ", DBHelper.ParamePrx);
                        object obj = cmd.ExecuteScalar();
                        if (obj != DBNull.Value)
                        {
                            byte[] buffer = (byte[])obj;
                            filestream = new MemoryStream(buffer);
                            isDownload = true;
                        }
                    }

                    #endregion
                }
                else
                {
                    #region 硬盘上下载
                    if (xeFile.Element("URL").GetValue() != "")
                    {
                        return null; 
                    }
                    else
                    {
                        if (File.Exists(xeFile.Element("LocalPath").Value))
                        {
                            filestream = new FileStream(FileManagement.FileRootPath + xeFile.Element("RelativePath").Value, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                            isDownload = true;
                        }
                        else
                        {
                            return null; //此处不宜扔出异常，会导致客户端下载到一个错误格式的word文件
                        }
                    }
                    #endregion
                }

                if (isDownload)
                {
                    //更新下载次数
                    using (TwiCommand cmd = DBHelper.CreateCommand())
                    {
                        cmd.SetParameter("DownloadCount", int.Parse(xeFile.Element("DownloadCount").Value) + 1);
                        cmd.SetParameter("FileID", fileID);
                        cmd.CommandText = string.Format("UPDATE gnl_File SET DownloadCount={0}DownloadCount WHERE FileID ={0}FileID ", DBHelper.ParamePrx);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            return filestream;
        }
        /// <summary>
        /// 返回byte数组
        /// </summary>
        /// <param name="fileID"></param>
        /// <returns></returns>
        public static byte[] GetFileByte(Guid fileID)
        {
            Stream filestream = null;
            byte[] buffer = null;
            XElement xeFile = GetFile(fileID);
            if (xeFile != null)
            {
                bool isDownload = false;
                if (xeFile.Element("STOREFLAG").GetValue<int>(0) == 2)
                {
                    #region 数据库中获得下载文件
                    using (TwiCommand cmd = DBHelper.CreateCommand())
                    {
                        cmd.SetParameter("FileID", fileID);
                        cmd.CommandText = string.Format("SELECT FileData FROM gnl_File WHERE FileID ={0}FileID ", DBHelper.ParamePrx);
                        object obj = cmd.ExecuteScalar();
                        if (obj != DBNull.Value)
                        {
                            buffer = (byte[])obj;
                            isDownload = true;
                        }
                    }

                    #endregion
                }
                else
                {
                    #region 硬盘上下载
                    if (xeFile.Element("URL").GetValue() != "")
                    {
                        return null;
                    }
                    else
                    {
                        if (File.Exists(xeFile.Element("LocalPath").Value))
                        {
                            filestream = new FileStream(FileManagement.FileRootPath + xeFile.Element("RelativePath").Value, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                            System.IO.BinaryReader br = new BinaryReader(filestream);
                            buffer = br.ReadBytes(Convert.ToInt32(filestream.Length));
                            br.Close();
                            filestream.Close();
                            isDownload = true;
                        }
                        else
                        {
                            return null; //此处不宜扔出异常，会导致客户端下载到一个错误格式的word文件
                        }
                    }
                    #endregion
                }

                if (isDownload)
                {
                    //更新下载次数
                    using (TwiCommand cmd = DBHelper.CreateCommand())
                    {
                        cmd.SetParameter("DownloadCount", int.Parse(xeFile.Element("DownloadCount").Value) + 1);
                        cmd.SetParameter("FileID", fileID);
                        cmd.CommandText = string.Format("UPDATE gnl_File SET DownloadCount={0}DownloadCount WHERE FileID ={0}FileID ", DBHelper.ParamePrx);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            return buffer;
        }
        /// <summary>
        /// 获取文件全名
        /// </summary>
        /// <param name="fileID">文件ID</param>
        /// <param name="tempDir">临时目录</param>
        /// <returns></returns>
        public static string GetFileFullName(Guid fileID, string tempDir)
        {
            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            string fileFullName = tempDir + Guid.NewGuid().ToString();

            XElement xeFile = GetFile(fileID);
            if (xeFile != null)
            {
                bool isDownload = false;
                if (xeFile.Element("STOREFLAG").GetValue<int>(0) == 2) //文件存储在数据库中
                {
                    #region 数据库中获得下载文件

                    using (TwiCommand cmd = DBHelper.CreateCommand())
                    {
                        cmd.SetParameter("FileID", fileID);
                        cmd.CommandText = string.Format("SELECT FileData FROM gnl_File WHERE FileID ={0}FileID ", DBHelper.ParamePrx);
                        object obj = cmd.ExecuteScalar();
                        if (obj != DBNull.Value)
                        {
                            File.WriteAllBytes(fileFullName, obj as byte[]);
                            isDownload = true;
                        }
                    }

                    #endregion
                }
                else
                {
                    if (File.Exists(xeFile.Element("LocalPath").Value))
                    {
                        File.Copy(xeFile.Element("LocalPath").Value, fileFullName);
                    }
                    else
                    {
                        return null; //此处不宜扔出异常，会导致客户端下载到一个错误格式的word文件
                    }
                }
                if (isDownload)
                {
                    //更新下载次数
                    using (TwiCommand cmd = DBHelper.CreateCommand())
                    {
                        cmd.SetParameter("DownloadCount", int.Parse(xeFile.Element("DownloadCount").Value) + 1);
                        cmd.SetParameter("FileID", fileID);
                        cmd.CommandText = string.Format("UPDATE gnl_File SET DownloadCount={0}DownloadCount WHERE FileID ={0}FileID ", DBHelper.ParamePrx);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            return fileFullName;
        }

        #region 获得文件信息
        /// <summary>
        /// 获得文件信息
        /// </summary>
        /// <param name="fileID">文件ID</param>
        /// <returns></returns>
        public static XElement GetFile(Guid fileID)
        {
            XElement xeFile = null;
            using (TwiCommand cmd = DBHelper.CreateCommand())
            {
                cmd.CommandText = string.Format(@"SELECT FileID, FileName, Extension, FileSize, FileCategory, UploadDate, DownloadCount, UploadUserID, RelativePath
, LocalPath, MachineName, Flag, LastUpdateDate, LastUpdateUserID, STOREFLAG FROM gnl_File WHERE Flag = 1 AND FileID = {0}FileID", DBHelper.ParamePrx);
                cmd.AddParameter("FileID", fileID);
                xeFile = cmd.GetSingleOrDefault("gnl_File");
            }
            return xeFile;
        }
        #endregion

    }
}
